package com.tsfyun.scm.service.impl.customer;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Snowflake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.tsfyun.common.base.config.OrikaBeanMapper;
import com.tsfyun.common.base.exception.ServiceException;
import com.tsfyun.common.base.util.TsfPreconditions;
import com.tsfyun.scm.dto.customer.CustomerAbroadDeliveryInfoDTO;
import com.tsfyun.scm.dto.customer.CustomerBankDTO;
import com.tsfyun.scm.entity.customer.Customer;
import com.tsfyun.scm.entity.customer.CustomerBank;
import com.tsfyun.scm.mapper.customer.CustomerBankMapper;
import com.tsfyun.scm.service.customer.ICustomerBankService;
import com.tsfyun.common.base.extension.ServiceImpl;
import com.tsfyun.scm.service.customer.ICustomerService;
import com.tsfyun.scm.util.TsfWeekendSqls;
import com.tsfyun.scm.vo.customer.CustomerBankVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.weekend.WeekendSqls;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *

 * @since 2020-03-03
 */
@Service
public class CustomerBankServiceImpl extends ServiceImpl<CustomerBank> implements ICustomerBankService {

    @Autowired
    private OrikaBeanMapper beanMapper;

    @Autowired
    private ICustomerService customerService;

    @Autowired
    private CustomerBankMapper customerBankMapper;

    @Autowired
    private Snowflake snowflake;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(CustomerBankDTO dto) {
       TsfPreconditions.checkArgument(Objects.nonNull(dto.getCustomerId()),new ServiceException("请选择客户"));
        Customer customer = customerService.getById(dto.getCustomerId());
        TsfPreconditions.checkArgument(Objects.nonNull(customer), new ServiceException("您选择的客户信息不存在"));
        CustomerBank customerBank = beanMapper.map(dto, CustomerBank.class);
        //默认地址信息处理
        if(Objects.equals(Boolean.TRUE,customerBank.getIsDefault())) {
            //需要设置为默认地址，需要取消之前设置的默认地址
            handleOldDefault(customer.getId());
        }
        super.saveNonNull(customerBank);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(CustomerBankDTO dto) {
        TsfPreconditions.checkArgument(Objects.nonNull(dto.getCustomerId()),new ServiceException("请选择客户"));
        CustomerBank oldCustomerBank = super.getById(dto.getId());
        TsfPreconditions.checkArgument(Objects.nonNull(oldCustomerBank),new ServiceException("您选择的数据不存在"));
        Customer customer = customerService.getById(dto.getCustomerId());
        TsfPreconditions.checkArgument(Objects.nonNull(customer),new ServiceException("您选择的客户信息不存在"));
        CustomerBank customerBank = beanMapper.map(dto,CustomerBank.class);
        customerBank.setDateCreated(oldCustomerBank.getDateCreated());
        customerBank.setCreateBy(oldCustomerBank.getCreateBy());
        customerBank.setDisabled(Objects.equals(dto.getDisabled(),Boolean.TRUE));
        customerBank.setIsDefault(Objects.equals(dto.getIsDefault(),Boolean.TRUE));
        //如果由非默认变为默认则需要处理之前设置的默认的
        if(!oldCustomerBank.getIsDefault() && customerBank.getIsDefault()) {
            handleOldDefault(customer.getId());
        }
        super.updateById(customerBank);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void activeDisable(Long id) {
        CustomerBank customerBank = super.getById(id);
        TsfPreconditions.checkArgument(Objects.nonNull(customerBank),new ServiceException("客户银行信息不存在"));
        customerBank.setDisabled(!customerBank.getDisabled());
        super.updateById(customerBank);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void setDefault(Long id) {
        CustomerBank  customerBank = super.getById(id);
        TsfPreconditions.checkArgument(Objects.nonNull(customerBank),new ServiceException("客户银行信息不存在"));
        Boolean currentDefault = customerBank.getIsDefault();
        if(Objects.equals(Boolean.TRUE,currentDefault)) {
            //以前是默认，则现在更改为非默认
            customerBank.setIsDefault(Boolean.FALSE);
        } else {
            //以前是非默认，现在置为默认，则需要取消以前的默认如果存在的话
            handleOldDefault(customerBank.getCustomerId());
            customerBank.setIsDefault(Boolean.TRUE);
        }
        super.updateById(customerBank);
    }

    @Override
    public void handleOldDefault(Long customerId) {
        CustomerBank update = new CustomerBank();
        update.setIsDefault(Boolean.FALSE);
        customerBankMapper.updateByExampleSelective(update, Example.builder(CustomerBank.class).where(WeekendSqls.<CustomerBank>custom()
                .andEqualTo(CustomerBank::getCustomerId, customerId)
                .andEqualTo(CustomerBank::getIsDefault,Boolean.TRUE)).build());
    }

    @Override
    public List<CustomerBankVO> select(Long customerId) {
        CustomerBank condition = new CustomerBank();
        condition.setCustomerId(customerId);
        condition.setDisabled(Boolean.FALSE);
        List<CustomerBank> list = super.list(condition);
        //按是否默认排序，然后按最后修改日期排序
        if(CollectionUtil.isNotEmpty(list)) {
            //先按是否默认排序然后按修改时间排序
            list = list.stream().sorted(Comparator.comparing(CustomerBank::getIsDefault).reversed().thenComparing(CustomerBank::getDateUpdated).reversed())
                    .collect(Collectors.toList());
            return beanMapper.mapAsList(list,CustomerBankVO.class);
        }
        return null;
    }

    @Override
    public PageInfo<CustomerBankVO> pageList(CustomerBankDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getLimit());
        return new PageInfo<>(customerBankMapper.list(dto));
    }

    @Override
    public CustomerBankVO detail(Long id) {
        CustomerBank customerBank = super.getById(id);
        TsfPreconditions.checkArgument(Objects.nonNull(customerBank),new ServiceException("客户银行信息不存在"));
        return beanMapper.map(customerBank,CustomerBankVO.class);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveList(Long customerId, List<CustomerBankDTO> customerDeliveryInfoDTOS) {
        if(CollUtil.isEmpty(customerDeliveryInfoDTOS)) {
            return;
        }
        //设置第一个启用的为默认
        Boolean isDefault = false;
        for(int i=0;i<customerDeliveryInfoDTOS.size();i++){
            CustomerBankDTO dto = customerDeliveryInfoDTOS.get(i);
            if(dto.getIsDefault() && dto.getDisabled() != true){
                isDefault=true;
            }
        }
        if(isDefault==false){
            for(int i=0;i<customerDeliveryInfoDTOS.size();i++) {
                CustomerBankDTO dto = customerDeliveryInfoDTOS.get(i);
                if (dto.getDisabled() != true) {
                    customerDeliveryInfoDTOS.get(i).setIsDefault(Boolean.TRUE);
                }
            }
        }
        removeByCustomerId(customerId);
        List<CustomerBank> data = Lists.newArrayListWithCapacity(customerDeliveryInfoDTOS.size());
        customerDeliveryInfoDTOS.stream().forEach(dto->{
            CustomerBank customerBank = new CustomerBank();
            customerBank.setId(snowflake.nextId());
            customerBank.setCustomerId(customerId);
            customerBank.setName(dto.getName());
            customerBank.setAccount(dto.getAccount());
            customerBank.setAddress(dto.getAddress());
            customerBank.setDisabled(dto.getDisabled());
            customerBank.setIsDefault(dto.getIsDefault());
            data.add(customerBank);
        });
        super.savaBatch(data);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeByCustomerId(Long customerId) {
        customerBankMapper.deleteByExample(Example.builder(CustomerBank.class).where(TsfWeekendSqls.<CustomerBank>custom().andEqualTo(false,CustomerBank::getCustomerId,customerId)).build());
    }

    @Override
    public List<CustomerBank> list(Long customerId) {
        CustomerBank supplierBank = new CustomerBank();
        supplierBank.setCustomerId(customerId);
        return super.list(supplierBank);
    }
}
